package cc.fs.video.myvideoproject.ui.fragment

import android.app.Fragment
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import cc.fs.video.myvideoproject.AppContext
import cc.fs.video.myvideoproject.R
import cc.fs.video.myvideoproject.beans.FileBean
import cc.fs.video.myvideoproject.beans.VideoBean
import cc.fs.video.myvideoproject.ui.MainActivity
import cc.fs.video.myvideoproject.ui.adapter.SelectFileAdapter
import cc.fs.video.myvideoproject.utils.bindView
import java.io.File
import java.util.*

/**
 * Created by fostion on 2015/10/13.
 */
class FavFileFragment : Fragment() {

    val recycleView: RecyclerView by bindView(R.id.recycleview)
    val files: ArrayList<FileBean> = ArrayList()
    val videos: ArrayList<VideoBean> = ArrayList()
    var adapter: SelectFileAdapter ?= null
    val parent: MainActivity by lazy {
        activity as MainActivity
    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater?.inflate(R.layout.fragment_fav_file,container,false)
    }

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //get data
        getFiles()

        adapter = SelectFileAdapter(files)
        recycleView.adapter = adapter
        recycleView.layoutManager = GridLayoutManager(activity, 3)

        adapter?.onClick = {
            file ->
            if(file.category!!.equals("dir")){
                parent.selectFile(file?.path ?: "")
            }
        }

    }

    fun getFiles(){
        videos.addAll(AppContext.getVideoList())
        for(video in videos){
            val file = File(video.path).parentFile
            if(!findVideoFile(file.absolutePath)){
                val fileBean = FileBean()
                fileBean.name = file.name
                fileBean.path = file.absolutePath
                fileBean.category = "dir"
                files.add(fileBean)
            }
        }
    }

    fun findVideoFile(path:String):Boolean{
        val result = false;
        for(file in files){
            if(file.path!!.equals(path)){
                return true
            }
        }
        return  result;
    }

}